package com.yindong.tabbar.utils;

import com.yindong.tabbar.bottom.BottomNavigationBar;
import com.yindong.tabbar.fraction.FractionAdapter;
import com.yindong.tabbar.fraction.FractionPageComponent;
import com.yindong.tabbar.model.TabBarInfoModel;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.ability.fraction.FractionManager;
import ohos.app.Context;

import java.util.List;

/**
 * tabbar初始化工具类
 *
 * @author      殷冬
 * @date        2021-01-19
 * @version     1.0.0
 */
public class TabBarInitUtil {

    private static final Float BOTTOM_TAB_BAR_TRANSPARENCY  = 1.0F;

    /**
     * 初始化组件
     *
     * @param abilitySlice              abilitySlice对象
     * @param tabBarInfoModelLists      tabbar配置信息
     */
    public static void initialization(AbilitySlice abilitySlice, Context context, List<TabBarInfoModel> tabBarInfoModelLists){
        // 获取底部导航栏对象
        BottomNavigationBar bottomNavigationBar = new BottomNavigationBar(abilitySlice, context).bottomNavigationBar;
        // 设置导航栏透明度
        bottomNavigationBar.setAlpha(BOTTOM_TAB_BAR_TRANSPARENCY);
        // 初始化底部导航栏
        bottomNavigationBar.initialization(tabBarInfoModelLists);
        // 获取Fraction管理器
        FractionManager fractionManager = getFractionManager(abilitySlice);
        if(fractionManager != null){
            // 创建Fraction适配器对象
            FractionAdapter fractionAdapter = new FractionAdapter(fractionManager);
            // 获取Fraction页面组件对象
            FractionPageComponent fractionPageComponent = new FractionPageComponent(context).fractionPageComponent;
            // 设置适配器
            fractionPageComponent.setAdapter(fractionAdapter);
            // 初始化选中Fraction
            fractionPageComponent.initAllFractionPage(tabBarInfoModelLists);
            // 设置tabbar点击事件的监听
            bottomNavigationBar.addBarSelectedChangeListener(((nextIndex, nextTabBarInfoModel, currentTabBarInfoModel) ->
                    fractionPageComponent.showCurrentFractionByIndex(nextIndex, nextTabBarInfoModel, currentTabBarInfoModel)));
        }
    }

    /**
     * 获取Fraction管理器对象
     *
     * @param abilitySlice      abilitySlice对象
     * @return
     */
    private static FractionManager getFractionManager(AbilitySlice abilitySlice){
        Ability ability = abilitySlice.getAbility();
        if(ability instanceof FractionAbility){
            FractionAbility fractionAbility = (FractionAbility) ability;
            return fractionAbility.getFractionManager();
        }
        return null;
    }
}
